/*
 * Copyright © YOLANDA. All Rights Reserved
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.qx.ddx;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.util.Log;

import com.qx.ddx.nohttplibrary.NoHttp;
import com.qx.ddx.util.Item;
import com.qx.ddx.util.SpInfo;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * Created in Oct 23, 2015 12:59:13 PM.
 *
 * @author YOLANDA;
 */
public class DDXApplication extends android.app.Application {

    private static DDXApplication _instance;
    private Map<String, ArrayList<Item>> orderList = new HashMap<String, ArrayList<Item>>();
    private String totalPrice = null;
    private String num = null;
    private ArrayList<Activity> activities = new ArrayList<Activity>();

    @Override
    public void onCreate() {
        super.onCreate();
        _instance = this;
        NoHttp.init(this);
    }

    public static DDXApplication getInstance() {
        return _instance;
    }

    public Map<String, ArrayList<Item>> getOrderList() {
        return orderList;
    }

    public void addActivity(Activity activity) {
        activities.add(activity);
    }

    public void quit() {
        int count = activities.size();
        for (int i = 0; i < count; i++) {
            activities.get(i).finish();
        }
    }

    public String getIPAndPort() {
        SharedPreferences sp = this.getSharedPreferences(SpInfo.Setting, Context.MODE_PRIVATE);
        String ip = sp.getString(SpInfo.Ip, "");
        String port = sp.getString(SpInfo.Port, "");
        if (ip.equals("") || port.equals("")) {
            return "";
        }
        return ip + ":" + port;
    }

    public String getIPStr() {
        SharedPreferences sp = this.getSharedPreferences(SpInfo.Setting, Context.MODE_PRIVATE);
        String ip = sp.getString(SpInfo.Ip, "");
        return ip;
    }

    public String getPortStr() {
        SharedPreferences sp = this.getSharedPreferences(SpInfo.Setting, Context.MODE_PRIVATE);
        String port = sp.getString(SpInfo.Port, "");
        return port;
    }

    public void insert(Item item) {
        if (orderList.containsKey(item.getCategoryName())) {
            if (upData(item)) {
                return;
            }
            ArrayList<Item> data = orderList.get(item.getCategoryName());
            data.add(item);
            orderList.put(item.getCategoryName(), data);
        } else {
            ArrayList<Item> data = new ArrayList<Item>();
            data.add(item);
            orderList.put(item.getCategoryName(), data);
        }
        sendBroadcastByDataChange();
    }


    public boolean upData(Item item) {
        ArrayList<Item> data = orderList.get(item.getCategoryName());
        for (int i = 0; i < data.size(); i++) {
            Item dataItem = data.get(i);
            if (dataItem.getId().equals(item.getId())) {
                if (item.getQuantity().equals("0")) {
                    data.remove(i);
                } else {
                    data.set(i, item);
                }
                orderList.put(item.getCategoryName(), data);
                sendBroadcastByDataChange();
                return true;
            }
        }
        return false;
    }

    public void addItemQuantity(String itemId, String categoryName) {
        ArrayList<Item> data = orderList.get(categoryName);
        for (int i = 0; i < data.size(); i++) {
            Item dataItem = data.get(i);
            if (dataItem.getId().equals(itemId)) {
                dataItem.setQuantity(String.valueOf(Integer.valueOf(dataItem.getQuantity()) + 1));
                data.set(i, dataItem);
                orderList.put(categoryName, data);
                sendBroadcastByDataChange();
                return;
            }
        }
    }

    public void reduceItemQuantity(String itemId, String categoryName) {
        ArrayList<Item> data = orderList.get(categoryName);
        for (int i = 0; i < data.size(); i++) {
            Item dataItem = data.get(i);
            if (dataItem.getId().equals(itemId)) {
                dataItem.setQuantity(String.valueOf(Integer.valueOf(dataItem.getQuantity()) - 1));
                data.set(i, dataItem);
                orderList.put(categoryName, data);
                sendBroadcastByDataChange();
                return;
            }
        }
    }

    public boolean delData(String itemId, String categoryName) {
        ArrayList<Item> data = orderList.get(categoryName);
        for (int i = 0; i < data.size(); i++) {
            Item dataItem = data.get(i);
            if (dataItem.getId().equals(itemId)) {
                data.remove(i);
                orderList.put(categoryName, data);
                sendBroadcastByDataChange();
                return true;
            }
        }
        return false;
    }

    private void sendBroadcastByDataChange() {
        setTotalPrice();
        Intent intent = new Intent();
        if (totalPrice == null)
            intent.putExtra(SpInfo.totalPrice, "0.0");
        else
            intent.putExtra(SpInfo.totalPrice, totalPrice);
        intent.setAction(SpInfo.OrderData);
        sendBroadcast(intent);
    }

    private void setTotalPrice() {
        Iterator iterator = orderList.entrySet().iterator();
        BigDecimal b1 = new BigDecimal("0.0");
        int num = 0;
        while (iterator.hasNext()) {
            Map.Entry<String, ArrayList<Item>> entry = (Map.Entry<String, ArrayList<Item>>) iterator.next();
            ArrayList<Item> val = entry.getValue();
            num = num + val.size();
            for (int i = 0; i < val.size(); i++) {
                Item item = val.get(i);
                String price = item.getPrice();
                String quantity = item.getQuantity();
                b1 = b1.add(new BigDecimal(price).multiply(new BigDecimal(quantity)));
            }
        }
        totalPrice = b1.toString();
        this.num = String.valueOf(num);
    }

    public String getJsonStr() {
        try {
            JSONArray jsonItem = new JSONArray();
            Iterator iterator = orderList.entrySet().iterator();
            while (iterator.hasNext()) {
                Map.Entry<String, ArrayList<Item>> entry = (Map.Entry<String, ArrayList<Item>>) iterator.next();
                ArrayList<Item> val = entry.getValue();
                for (int i = 0; i < val.size(); i++) {
                    Item item = val.get(i);
                    JSONObject obj = new JSONObject();
                    int id = Integer.valueOf(item.getId());
                    double quantity = Float.valueOf(item.getQuantity()) + 0.1;
                    Log.i("DDXApplication", "id: " + id + "    quantity: " + quantity);
                    obj.put("item_id", id);
                    obj.put("quantity", quantity);
                    jsonItem.put(obj);
                }
            }
            return jsonItem.toString();
        } catch (JSONException e) {
            Log.e("DDXApplication", "orderRequest JSONException:" + e.toString());
        }
        return "";
    }

    public boolean isEmpty() {
        return orderList.isEmpty();
    }

    public String getTotalPrice() {
        if (totalPrice == null)
            return "0.0";
        else
            return totalPrice;
    }

    public String getTotalNumber() {
        if (num == null)
            return "0";
        else
            return num;
    }
}
